<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Easing 3D</title>
    <link rel="stylesheet" href="../include/style.css">
  </head>
  <body>
    <header>
      Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
    </header>
    <canvas id="canvas" width="400" height="400"></canvas>

    <script src="../include/utils.js"></script>
    <script src="./classes/ball3d.js"></script>
    <script>
    window.onload = function () {
      var canvas = document.getElementById('canvas'),
          context = canvas.getContext('2d'),
          ball = new Ball3d(),
          tx = Math.random() * 500 - 250,
          ty = Math.random() * 500 - 250,
          tz = Math.random() * 500,
          easing = 0.1,
          fl = 250,
          vpX = canvas.width / 2,
          vpY = canvas.height / 2;

      (function drawFrame () {
        window.requestAnimationFrame(drawFrame, canvas);
        context.clearRect(0, 0, canvas.width, canvas.height);
        
        var dx = tx - ball.xpos,
            dy = ty - ball.ypos,
            dz = tz - ball.zpos,
            dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
        
        ball.xpos += dx * easing;
        ball.ypos += dy * easing;
        ball.zpos += dz * easing;
        
        if (dist < 1) {
          tx = Math.random() * 500 - 250;
          ty = Math.random() * 500 - 250;
          tz = Math.random() * 500;
        }
        if (ball.zpos > -fl) {
          var scale = fl / (fl + ball.zpos);
          ball.scaleX = ball.scaleY = scale;
          ball.x = vpX + ball.xpos * scale;
          ball.y = vpY + ball.ypos * scale;
          ball.visible = true;
        } else {
          ball.visible = false;
        }
        if (ball.visible) {
          ball.draw(context);
        }
      }());
    };
    </script>
  </body>
</html>
